package com.pan.kang.support;

import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class SpringContextUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;
    private static final Map<String, Object> springBeanCache = new ConcurrentHashMap<>(1024);

    public static <T> T getBean(Class<T> clazz) {
        String key = clazz.getSimpleName().toUpperCase(Locale.ROOT);
        T bean = (T) springBeanCache.get(key);
        if (null == bean) {
            bean = applicationContext.getBean(clazz);
            springBeanCache.putIfAbsent(key, bean);
        }
        return bean;
    }

    @Override
    public void setApplicationContext(@NotNull ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.applicationContext = applicationContext;
    }
}
